import { createRouter, createWebHistory } from 'vue-router'
import { useTokenStore } from '@/store/token'
import { ElMessage } from 'element-plus';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', redirect: '/home'},
    { path: '/login',component: () => import('@/views/system/Login.vue'), },
    { path: '/',component: () => import('@/views/system/Layout.vue'), 
      children: [
        { path: 'home', meta: { name: "主页"}, component: () =>  import('../views/system/Home.vue'), },
        { path: 'admin', meta: { name: "管理员信息"}, component: () =>  import('../views/user/Admin.vue'), },
        { path: 'user', meta: { name: "普通用户信息"}, component: () =>  import('../views/user/User.vue'), },
        { path: 'person', meta: { name: "个人中心"}, component: () =>  import('../views/system/Person.vue'), },
        { path: 'info/notice', meta: { name: "系统公告"}, component: () =>  import('../views/system/Notice.vue'), },
        { path: 'data', meta: { name: "数据统计"}, component: () =>  import('../views/future/EchartsData.vue'), },
        { path: 'article/manager', meta: { name: "文章管理"}, component: () =>  import('../views/article/Article.vue'), },
        { path: 'article/category', meta: { name: "文章分类"}, component: () =>  import('../views/article/Category.vue'), },
      ]
    },

//  其他路由都跳转到404页面
    { path: '/notfound',component: () =>  import('../views/system/404.vue'), },
    { path: '/:pathMatch(.*)', redirect:'/notfound', },
  ],
})

// 路由守卫跳转登录页
// 路由守卫优先于响应拦截器，因为在跳转到该路由的时候就在判断是否登录，而不是请求了之后才判断是否登录
router.beforeEach((to, from, next) => {
  // 这里注意到，tokenstore的获取需要放在router的beforeeach的里面， 官网说的
  const tokenStore = useTokenStore();
  if (to.path !== '/login' && !tokenStore.token) {
    ElMessage.error('您还未登录，请先登录！')
    next('/login'); // 未登录且访问非登录页，跳转到登录页
  } else {
    next();
  }
});
export default router
